import {ListGroup} from "@bpmn-io/properties-panel";
import {
    getExtensionElementsList,
    getImplementationType,
    implementationExecutionListenerDetails
} from "@/components/activiti/util";
import {addListenerFactory, getListenersContainer, implementationDetails, removeListenerFactory} from "../util"

const executionListenerGroup = {
    id: 'executionListener',
    label: 'Execution listeners',
    component:ListGroup,
    function:function (groups,element, translate,injector,register){
        let a = ExecutionListenerProps({
            element,
            translate,
            injector,
            register
        })
        return a;
    }
};
export default executionListenerGroup

function ExecutionListenerProps(props) {
    const {
        element,injector,register
    } = props;
    const bpmnFactory = injector.get('bpmnFactory'),
        commandStack = injector.get('commandStack');
    const translate = injector.get('translate');
    const type = "activiti:ExecutionListener"
    const businessObject = getListenersContainer(element);
    const listeners = getExtensionElementsList(businessObject, type) || [];
    const items = []
    for (let i = 0; i < listeners.length; i++) {
        let id = element.id + '-listener-' + i;
        let listener = listeners[i];
        items.push({
            id,
            label: getListenerLabel(listener,translate),
            entries: getEntries(element,id,register,translate,listener),
            autoFocusEntry: id + '-name',
            remove: removeListenerFactory({ commandStack, element, listener, type })
        })
    }
    return {
        items,
        add: addListenerFactory({ element, bpmnFactory, commandStack,type })
    };
}
const IMPLEMENTATION_TYPE_TO_LABEL = {
    class: 'Java class',
    expression: 'Expression',
    delegateExpression: 'Delegate expression'
};
function getListenerLabel(listener, translate) {
    const event = listener.get('event');
    const implementationType = getImplementationType(listener);
    const b = translate(IMPLEMENTATION_TYPE_TO_LABEL[implementationType]);
    return `${event}: ${b}`;
}

function getEntries(element,id,register,translate,listener){
    let arrs = ['eventType','onTransaction','listenerType'];
    const  list = []
    for (let i = 0; i < arrs.length; i++) {
        let entries = register.findEntries(arrs[i],translate)
        entries = {...entries}
        entries.id = id;
        entries.listener =listener;
        list.push(entries)
    }
    implementationExecutionListenerDetails(element,id,register,translate,listener,list);
    return list
}

